package com.nil.codegen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nil.codegen.constants.SysConstants;
import com.nil.codegen.domain.dto.DbDriverDTO;
import com.nil.codegen.domain.dto.DbDriverQueryDTO;
import com.nil.codegen.domain.vo.DbDriverVO;
import com.nil.codegen.exception.BusinessException;
import com.nil.codegen.mapper.DbDriverMapper;
import com.nil.codegen.service.IDbDriverService;
import com.nil.codegen.domain.entity.DbDriver;
import com.nil.codegen.utils.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;


@Service
public class DbDriverServiceImpl extends ServiceImpl<DbDriverMapper, DbDriver> implements IDbDriverService {

    @Override
    public void saveDbDriver(DbDriverDTO dbDriverDTO) {

        LambdaQueryWrapper<DbDriver> wrapper = Wrappers.lambdaQuery(DbDriver.class)
                .eq(DbDriver::getName, dbDriverDTO.getName())
                .eq(DbDriver::getDeleteFlag, SysConstants.NOT_DELETE);
        long count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new BusinessException("驱动名称已存在!");
        }

        DbDriver dbDriver = new DbDriver();
        dbDriver.setId(DateUtil.getUUID());
        BeanUtils.copyProperties(dbDriverDTO,dbDriver);
        this.save(dbDriver);
    }


    @Override
    public PageInfo<DbDriverVO> pageList(DbDriverQueryDTO queryDTO) {
        try (Page<Object> ignore = PageHelper.startPage(queryDTO.getPageNum(), queryDTO.getPageSize())){
            List<DbDriverVO> dbDriverVOS = baseMapper.selectList(queryDTO);
            return new PageInfo<>(dbDriverVOS);
        }
    }

    @Override
    public List<DbDriverVO> listAll() {
        DbDriverQueryDTO queryDTO = new DbDriverQueryDTO();
        return baseMapper.selectList(queryDTO);
    }


    @Override
    public DbDriverVO getById(String driverId) {
        return baseMapper.selectById(driverId);
    }
}
